import { _decorator, Component, Node, Prefab, instantiate, UITransform, Animation, Vec3, Input, input, sys, Collider2D, Contact2DType, IPhysics2DContact, Sprite } from 'cc';
import { data } from '../../data';
import { G } from '../../G';
const { ccclass, property } = _decorator;

@ccclass('arcadeScene')
export class arcadeScene extends Component {

    private player: Node;
    private score: Node;

    start() {
        // 初始化
        G.startGame(this.node)
        // 制作分数
        this.score = G.gameRoot.scoreInit(this.node)
        // 制作玩家
        this.player = G.gameRoot.playerInit(this.node, data.playerSelected)
        // 玩家碰撞监听
        let collider = this.player.getComponent(Collider2D)
        if (collider) {
            collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this)
            collider.on(Contact2DType.END_CONTACT, this.onEndContact, this)
        }
    }

    update(deltaTime: number) {
        G.gameUpdate(this.player, this.node, this.score, "arcade")
    }

    /**
     * 街机模式的玩家碰撞检测
     * @param self 
     * @param other 
     * @param contact 
     */
    onBeginContact(self: Collider2D, other: Collider2D, contact: IPhysics2DContact | null) {
        // 上柱子
        if (other.node.name === 'up') {
            if (self.worldAABB.yMax > other.worldAABB.yMin && (self.worldAABB.xMax - other.worldAABB.xMin) > 20) {
                // 碰到了上柱子的下面
                data.isContactPipeUp = true
                // 记录柱子yMin
                data.pipeUpYMin = other.worldAABB.yMin
                // 让小鸟立刻下降
                data.distanceY = 0
            } else {
                // 鸟开始向后
                data.isPlayerBackward = true
            }
        } else if (other.node.name === 'down') {
            // 下柱子
            if (self.worldAABB.yMin < other.worldAABB.yMax && (self.worldAABB.xMax - other.worldAABB.xMin) > 20) {
                // 碰到了下柱子的上面
                data.isContactPipeDown = true
                // 记录柱子yMax
                data.pipeDownYMaxX = this.player.getWorldPosition().x
                data.pipeDownYMax = other.worldAABB.yMax + this.player.getComponent(UITransform).contentSize.height / 2 - 3
            } else {
                // 鸟开始向后
                data.isPlayerBackward = true
            }
        }
    }

    /**
     * 街机模式的玩家碰撞检测
     * @param self 
     * @param other 
     * @param contact 
     */
    onEndContact(self: Collider2D, other: Collider2D, contact: IPhysics2DContact | null) {
        if (other.node.name === 'up') {
            // 离开上柱子的下面
            data.isContactPipeUp = false
        } else if (other.node.name === 'down') {
            // 离开下柱子的上面
            data.isContactPipeDown = false
        }
        // 鸟停止向后
        data.isPlayerBackward = false
    }
}


